<script setup lang="ts">
import { reactive, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { colTableConfig } from '#/views/onlineDesign/designPage/template/colTable/config';
import { sortSeq } from '#/views/onlineDesign/designPage/template/methods/commonMethod';

const record = ref({});
const [Form, formApi] = useVbenForm(
  reactive({
    ...colTableConfig.form.base,
    schema: [],
  }),
);

const [Modal, modalApi] = useVbenModal({
  title: 'xxx',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      message.success(record.value.title);
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}${record.value.title}`,
      });
      initFun();
    }
  },
});

async function initFun() {
  const selectedItems = colTableConfig.form.options.filter(
    (item) => item.extra.showSelect,
  );
  await formApi.setState({ schema: selectedItems });
}

async function onSubmit() {
  message.success('onSubmit');
}

// 监听查询表单配置变化
watch(
  () => colTableConfig.form.base,
  async (val) => {
    await formApi.setState(val);
  },
  { deep: true },
);

// 更新表单排序
async function updateFormSort() {
  await sortSeq(colTableConfig.form.options);
  await formApi.setState({
    schema: colTableConfig.form.options,
  });
  message.success('排序更新成功');
}
</script>

<template>
  <Modal>
    <template #description>
      <div class="mt-2 flex justify-between">
        <div style="color: red">注意：无法进行添加和编辑数据</div>
        <a-button type="primary" danger size="small" @click="updateFormSort">
          更新字段排序
        </a-button>
      </div>
    </template>
    <Form />
  </Modal>
</template>
